<template>
  <div id="cloud" class="">
    <!-- <zip-list></zip-list> -->
    <div id="menu-card" class="mdui-center">
      <h1 class="mdui-center">
        <!-- <img src="@/assets/cloud_1.png" alt="Logo"> -->
        <strong class="mdui-text-color-blue">MyCloud</strong>
      </h1>
      <div class="mdui-center">
        <div id="path-bar" class="mdui-typo">
          <!-- <span>当前路径: </span> -->
          <ul class="path-bar mdui-typo">
            <li><a href="/#/cloud">Home</a></li>
            <li v-for="(item, index) in nowPathList" :key="index">
              <a
                @click="changPage(index)"
                :disabled="index == nowPathList.length"
                >{{ item }}</a
              >
            </li>
          </ul>
        </div>
        <!-- tools menu -->
        <div class="mdui-toolbar">
          <!-- upload File -->
          <a
            class="mdui-btn mdui-btn-icon"
            @click="selectFile()"
          >
            <i class="mdui-icon material-icons">file_upload</i>
          </a>
          <input
            ref="uploadInput"
            type="file"
            style="display: none"
          >
          <!-- create Folder -->
          <a
            class="mdui-btn mdui-btn-icon"
            @click="createFolder()"
            ><i class="mdui-icon material-icons">create_new_folder</i>
          </a>
          <!-- unzip btn -->
          <a
            class="mdui-btn mdui-btn-icon"
            @click="openZipList()"
            mdui-dialog="{target: '#zipFile'}"
          >
            <i class="mdui-icon material-icons">unarchive</i>
          </a>
          <a
            class="mdui-btn mdui-btn-icon"
            @click="refresh()"
          >
            <i class="mdui-icon material-icons">autorenew</i>
          </a>
        </div>
      </div>
    </div>
    <!-- loadding roll -->
    <div class="mdui-progress" v-show="loadding">
      <div class="mdui-progress-indeterminate"></div>
    </div>
    <!-- upload message -->
    <div class="mdui-progress" v-show="isUpload">
      <div class="mdui-progress-determinate" :style="{'width': uploadMessage + '%'}"></div>
    </div>
    <!-- fileBrowes -->
    <div id="cloud-file-list">
      <ul class="list-container">
        <li class="list-item">
          <div class="file-name">文件名</div>
          <div class="file-size">大小</div>
          <div class="file-date">最后修改时间</div>
        </li>
        <!-- 返回上一层 -->
        <li class="list-item mdui-ripple tool-bar"
          style="overflow: hidden"
          @click="goback()"
          >
          <div class="file-name mdui-valign">Go Back</div>
          <div class="file-size"></div>
          <div class="file-date"></div>
        </li>
        <!-- 进入文件夹（列表文件夹items） -->
        <li
          class="list-item mdui-ripple dir"
          style="overflow: hidden"
          v-for="(item, index) in dataList.dirs"
          :key="'dir' + index"
          @click="enterDir(item.name)"
        >
          <div class="file-name mdui-valign">{{ item.name }}</div>

          <div class="file-size">-</div>
          <div class="file-date">{{ item.date | formatDate }}</div>
        </li>
        <li
          class="list-item mdui-ripple file"
          style="overflow: hidden"
          v-for="(item, index) in dataList.files"
          :key="'file' + index"
          @click="downloadFile(item.name)"
        >
          <div class="file-name mdui-valign">{{ item.name }}</div>
          <div class="file-size">{{ item.size | formatSize }}</div>
          <div class="file-date">{{ item.date | formatDate }}</div>
          <button
            class="mdui-btn mdui-btn-icon mdui-ripple"
            @click.stop="del($event, item.name)"
            >
            <i class="mdui-icon material-icons">&#xe872;</i>
          </button>
        </li>
      </ul>
    </div>
    <!-- zipFiles -->
    <div class="mdui-dialog" id="zipFile">
      <div class="mdui-dialog-content">
        <div class="mdui-dialog-title">解压文件列表</div>
        <label
          class="mdui-list-item mdui-ripple"
          v-for="(item, index) in FileList"
          :key="index"
        >
          <div class="mdui-checkbox">
            <input
              type="checkbox"
              :checked="item.choice"
              v-model="selectList"
              :value="item.name"
            />
            <i class="mdui-checkbox-icon"></i>
          </div>
          <div class="mdui-list-item-content">
            {{ item.name }}
          </div>
          <!-- <i class="mdui-list-item-icon mdui-icon material-icons">chat</i> -->
        </label>
        <div class="mdui-dialog-actions">
          <button id="zipFileClose" class="mdui-btn mdui-ripple" mdui-dialog-close>取消</button>
          <button
            class="mdui-btn mdui-ripple"
            @click="unzip()"
            mdui-dialog-close
            >
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import sizeFormat from '@/utils/sizeFormat'
import apiConfig from '@/api/apiConfig'
import mdui from 'mdui'

export default {
  data () {
    return {
      dataList: {
        dirs: [],
        files: []
      },
      loading: false,
      nowPath: './',
      nowPathList: [],
      prefix: '/cloud',
      uploadMessage: 0,
      newFolderName: '',
      FileList: [],
      selectList: [],
      loadding: false,
      isUpload: false
    }
  },
  filters: {
    formatSize (input) {
      return sizeFormat.formatSizeString(input)
    },
    formatDate (input) {
      return sizeFormat.formatDateString(input)
    }
  },
  methods: {
    changPage (index) {
      try {
        if (index === -1) {
          this.$router.push('/cloud')
        }
        const targetPath = Array(this.nowPathList.slice(0, index + 1))[0].join('/')
        if (targetPath !== this.nowPath) {
          this.$router.push('/cloud/' + targetPath)
        }
      } catch (err) {
        console.log(err)
      }
    },
    updataPath () {
      try {
        console.log('now route path ->', this.$route.path)
        this.nowPathList = this.$route.path
          .substring(`/${this.prefix}`.length)
          .split('/')
          .filter((i) => i.length > 0)
        this.nowPath = `./${this.nowPathList.join('/')}`
      } catch (error) {
        console.log(error)
      }
      console.log('当前目录->', this.nowPath)
    },
    async loadList () {
      if (this.loading) {
        return
      }
      try {
        console.log('loadList.path->', this.nowPath)
        this.loadding = true
        const conf = apiConfig.cloud.loadFile(this.nowPath)
        const datas = await this.$axios(conf)
        console.log(datas)
        this.dataList = datas.data.data
      } catch (error) {
        console.log('loadList', error.message)
        mdui.snackbar({
          message: error.message,
          position: 'top'
        })
      } finally {
        this.$nextTick(function () {
          this.loadding = false
          console.log('list was loaded!')
          console.log('loadList.path->', this.nowPath)
        })
      }
    },
    goback () {
      if (this.nowPathList.length === 0) {
        return
      }
      this.nowPathList.pop()
      location.href = `/#${this.prefix}/${this.nowPathList.join('/')}`
      this.updataPath()
    },
    enterDir (dirName) {
      let toPath = `${this.prefix}/${this.nowPathList.join('/')}/${dirName}`
      if (this.nowPathList.length === 0) {
        toPath = `${this.prefix}/${this.nowPathList.join('/')}${dirName}`
      }
      this.$router.push(toPath)
    },
    downloadFile (filename) {
      let downPath = `${this.nowPath}/${filename}`
      if (this.nowPath === './') {
        downPath = `${this.nowPath}${filename}`
      }

      const downloadForm = document.createElement('form')
      const tokenInput = document.createElement('input')
      const pathInput = document.createElement('input')
      // 构建表单
      downloadForm.method = 'POST'
      downloadForm.style.display = 'none'
      downloadForm.action = `${apiConfig.server}/download/private`
      tokenInput.name = 'token'
      tokenInput.value = this.$store.state.token
      pathInput.name = 'path'
      pathInput.value = downPath
      downloadForm.appendChild(tokenInput)
      downloadForm.appendChild(pathInput)

      // 添加表单到页面 && 下载
      document.body.appendChild(downloadForm)
      downloadForm.submit()
      document.body.removeChild(downloadForm)
    },
    selectFile () {
      this.$refs.uploadInput.onchange = this.upload
      this.$refs.uploadInput.click()
    },
    async upload () {
      const conf = apiConfig.cloud.uploadFile(
        this.$refs.uploadInput.files,
        this.nowPath,
        progressEvent => {
          const complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
          console.log('上传 ' + complete)
          this.uploadMessage = parseInt(complete)
        }
      )
      try {
        this.isUpload = true
        await this.$axios(conf)
        this.isUpload = false
        this.loadList()
      } catch (error) {
        console.log('错误处理: ')
        console.log(error)
      } finally {
        this.$refs.uploadInput.value = ''
      }
    },
    createFolder () {
      const _this = this
      mdui.prompt('请输入新文件夹的名字',
        async function (value) {
          try {
            _this.newFolderName = value
            const conf = apiConfig.cloud.newFolder(_this.nowPath, _this.newFolderName)
            await _this.$axios(conf)
            _this.loadList()
          } catch (error) {
            console.log(error)
          }
          // _this.$axios.
        })
      console.log(this.newFolderName)
    },
    openZipList () {
      // const zipFiles = []
      this.FileList = []
      this.dataList.files.forEach(e => {
        if (e.type === '.zip') {
          e.choice = false
          this.FileList.push(e)
        }
      })
      if (this.FileList.length === 0) {
        mdui.snackbar('当前文件夹未找到可解压文件', {
          position: 'top',
          timeout: 2000
        })
      }
    },
    unzip () {
      this.selectList.forEach(async element => {
        try {
          const conf = apiConfig.cloud.zipFile(this.nowPath, element)
          await this.$axios(conf)
        } catch (error) {
          console.log(error)
          this.loadList()
        }
      })
      mdui.snackbar('服务器正在解压，一会刷新看看趴', { timeout: 2000, position: 'top' })
    },
    refresh () {
      this.loadList()
    },
    async del (e, filename) {
      const conf = apiConfig.cloud.delFile(this.nowPath, filename)
      try {
        const resp = await this.$axios(conf)
        mdui.snackbar({
          message: resp.data.message,
          position: 'top',
          timeout: 2000
        })
      } catch (error) {
        console.log('err', error)
      }
      this.refresh()
    }
  },
  watch: {
    $route (to, from) {
      if (to.path !== from.path) {
        console.log('路由变化，更新中...')
        this.updataPath()
        this.loadList()
      }
    }
  },
  mounted () {
    this.updataPath()
    this.loadList()
  },
  beforeRouteEnter (to, from, next) {
    if (localStorage.getItem('token')) {
      next()
    } else {
      mdui.snackbar({
        message: '请先登录！',
        position: 'top',
        timeout: 1000,
        onClosed: _ => {
          next('/login')
        }
      })
    }
  },
  components: {
    // 'zip-list': zipFileList
  }
}
</script>

<style scoped>
#cloud {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  margin: 0 auto;
  width: calc(100% - 20px);
  max-width: 600px;
  /* animation: 0.5s showCloud ease-in; */
}
@keyframes showCloud {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
#cloud-file-list {
  margin: 0 auto;
  width: 100%;
  /* max-width: 500px; */
}
.dir {
  background-image: url();
}
.file {
  background-image: url();
}
.tool-bar {
  background-image: url();
  background-size: 16px 16px;
  background-position: 10px;
}
.list-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0;
  padding: 0;
  opacity: 0.95;
  max-width: 600px;
}

.list-container .list-item {
  display: flex;
  flex-direction: row;
  /* 不换行 */
  flex-wrap: nowrap;
  font-size: 12px;
  align-items: center;
  justify-content: space-around;
  padding: 0 10px;
  height: 45px;
  width: calc(100% - 20px);
  max-width: 600px;
  background-repeat: no-repeat;
  background-position-y: 10px;
  background-position-x: 10px;
  background-size: 24px 24px;
  cursor: pointer;
}
.list-container .list-item > * {
  display: flex;
  align-items: center;
}
.list-container .list-item > div {
  height: 100%;
  overflow: hidden;
  flex-shrink: 0;
  flex-basis: 0;
}
.list-container .dir:hover,
.list-container .file:hover {
  background-color: #e9e9e9;
}
.file-name {
  flex-grow: 6;
  padding-left: 35px;
  text-overflow: ellipsis;
  text-align: left;
}
.file-size {
  flex-grow: 3;
  padding: 0 5px;
}
.file-date {
  flex-grow: 3;
  /* order: 2; */
}
.path-bar {
  cursor: pointer;
  border-bottom: 1.5px solid #efefef;
}
h1 {
  font-size: 48px;
}
.path-bar {
  display: inline-block;
  margin: 0;
  padding: 0;
  font-size: 16px;
}
.path-bar li {
  display: inline-block;
  color: blue;
}
.path-bar li a {
  display: inline-block;
  padding: 0 2px;
}
.path-bar li + li::before {
  content: ">";
  color: #a0a0a0;
  font-size: 12px;
  margin: 0 3px;
}
</style>
